package com.linkgie.galaxyframework.persistence.data;

import java.util.Iterator;

import com.linkgie.galaxyframework.utils.service.ServiceContext;

/**
 * 实体查询器工厂；
 */
public class EntityQueryFactory {

    private static DbPersistenceDriverSPI DRIVER_SPI;



    private synchronized static DbPersistenceDriverSPI lookupDriverSpi() {
        if (DRIVER_SPI != null) {
            return DRIVER_SPI;
        }
        ServiceContext<DbPersistenceDriverSPI> spiContext = ServiceContext.load(DbPersistenceDriverSPI.class);
        if (spiContext.getSize() == 0) {
            String errorMessage = "No DbQueryDriverSPI found.";
            throw new IllegalStateException(errorMessage);
        }
        if (spiContext.getSize() > 1) {
            Iterator<DbPersistenceDriverSPI> spiIterator = spiContext.getServices().iterator();
            String spiName1 = spiIterator.next().getClass().getName();
            String spiName2 = spiIterator.next().getClass().getName();

            String errorMessage = "More than one DbQueryDriverSPI found.\n" + spiName1 + "\n" + spiName2 + "\n...";
            throw new IllegalStateException(errorMessage);
        }
        DRIVER_SPI = spiContext.getFirstService();
        return DRIVER_SPI;
    }

    private static DbPersistenceDriver getDbQueryDriver() {
        if (DRIVER_SPI == null) {
            lookupDriverSpi();
        }
        return DRIVER_SPI.getDbQueryDriver();
    }

    private EntityQueryFactory() {
    }
    
    /**
     * 从指定实体类型创建一个查询器；
     * 
     * @param <T>
     * @param entityClass
     * @return
     */
    public static <T> EntityQuerier<T> from(Class<T> entityClass) {
        return getDbQueryDriver().createQuerier(entityClass);
    }

}
